(function(angular) {
	"use strict";
	angular.module("fs.waf").controller("cls.settlement.summaryController", summaryController);
	summaryController.$inject = [ "$scope", "$q", "$filter", "modalService", "gridService", "layoutConfig", "validatorConfig", "authService", "settlementSummaryService", "settlementPaymentService", "settlementInitService", "custPayService", "directChargeService", "glEntryService" ];
	function summaryController($scope, $q, $filter, modalService, gridService, layoutConfig, validatorConfig, authService, settlementSummaryService, settlementPaymentService, settlementInitService, custPayService, directChargeService, glEntryService) {
		var ctrl = this, params = $scope.$stateParams.params, errorMessage = {}, settlement = {};
		
		ctrl.validatorConfig = validatorConfig;
		ctrl.setlDetailsConfig = layoutConfig.formConfigs.setlDetailView.tableConfigs.setlDetails.columnDefs;
		ctrl.init = function() {
			ctrl.txnSetlInsts = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.txnSetlInsts.tableConfigs.txnSetlInsts, null);
			ctrl.txnSetlInsts.data = "vm.settlement.txnSetlInsts";
			
			ctrl.paidLoanTableConfig = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.paidLoans.tableConfigs.paidLoans, null);
			ctrl.paidLoanTableConfig.data = "vm.settlement.loan.loanPaidLoans";
			
			ctrl.paidCustpayTableConfig = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.paidCustpays.tableConfigs.paidCustpays, null);
			ctrl.paidCustpayTableConfig.data = 'vm.settlement.loan.loanPaidCustpays';
			var defer1 = $q.defer(), defer2 = $q.defer(), defer3 = $q.defer(), defer4 = $q.defer();
			settlementSummaryService.getFxRateTypes().then(function(fxRateTypes){
				settlement.fxRateTypes = fxRateTypes;
				defer1.resolve();
			});
			settlementPaymentService.settlementPaymentOptions().then(function(map) {
				settlement.deliveryTypeOptions = map.deliveryTypeOptions;
				settlement.currencyOptions = map.currencyOptions;
				settlement.allPartyTypeOptions = map.partyTypeOptions;
				settlement.swiftCaseList = map.swiftCaseList;
				defer2.resolve();
			});
			custPayService.initLogDataOptions().then(function(data){
				ctrl.payCcyOptions = data.currency;
				ctrl.countryOptions = data.country;
				ctrl.prodTypeOptions = data.prodType;
				defer3.resolve();
			});
			directChargeService.initDataOptions().then(function(map){
				ctrl.prodTypeOptions = map.productType;
				ctrl.countryOptions = map.country;
				ctrl.refCcyOptions = map.refCcy;
				ctrl.allocCodeOptions = map.allocCode;
				ctrl.communityIdOptions = map.communityId;
				defer4.resolve();
			});
			($q.all({
				defer1 : defer1.promise,
				defer2 : defer2.promise,
				defer3 : defer3.promise,
				defer4 : defer3.promise
			})).then(function(){
				authService.summary(params).then(function(response) {
					settlement = angular.merge(settlement, response.data.model);
					settlementSummaryService.processLoanPaidLoans(settlement.loan.loanPaidLoans);
					settlementSummaryService.processLoanPaidCustpays(settlement.loan.loanPaidCustpays);
					settlement.taskId = response.data.task.taskId || params.taskId;
					settlementSummaryService.initData(settlement);
					
					angular.extend(ctrl, settlementPaymentService.getPayDetailsConfig(settlement, layoutConfig));
					ctrl.payPartyConfig = settlementPaymentService.initData(settlement, layoutConfig);
					processTxnSetlInsts(settlement);
					getGlEntryList(ctrl, settlement);
					ctrl.isRollover = settlementSummaryService.isRollover(settlement);
					settlementInitService.getLayout(settlement, "summary").then(function(layout) {
						layoutConfig = layout || layoutConfig;
						settlementInitService.processDynaparmConfig(settlement.settlementInfo, layoutConfig);
						ctrl.generalConfig = settlementInitService.getGeneralConfig(settlement.settlementInfo, layoutConfig);
						ctrl.layoutConfig = layoutConfig;
						ctrl.settlement = settlement;
						displayWfInfo(response);
					});
				});
			});
		};
		
		ctrl.isDetailsPay = function(item){
			return settlementSummaryService.isDetailsPay(item);
		};
		
		ctrl.isDetailsReceive = function(item){
			return settlementSummaryService.isDetailsReceive(item);
		};
		
		function getGlEntryList(ctrl, settlement){
			glEntryService.getGlentryList($scope, layoutConfig, settlement.settlementInfo.parentId, "CLS:" + settlement.settlementInfo.parentType).then(function(response){
				ctrl.glEntryListConfig = response.glEntryListConfig;
				ctrl.glEntryList = response.glEntryList;
			});
		};
		
		function processTxnSetlInsts(settlement){
			if(settlement.txnSetlInsts){
				angular.forEach(settlement.txnSetlInsts, function(data, index, array){
					data.paycodeName = data.paycode ? data.paycode.substr(7) : "";
					data.itemType_desc = $filter("translate")("label.settlement.init." + data.itemType.toLowerCase());
				});
			}
		}
		
		function displayWfInfo(response){
			var messages = [];
			
			if(response.data.task.taskProps.wfInfo){
				var msg = new Object();
				msg.args = response.data.task.taskProps.wfInfo.msgParams || "";
				msg.msg = response.data.task.taskProps.wfInfo.msgCode || "cls.error.unknow.exception";
				messages.push(msg);
			}
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			}
		};
		
		ctrl.settlementSummary = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else {
				return authService.settlementSummary(ctrl.settlement).then(submitSuccessful, submitFailed);
			}
		};
		
		ctrl.viewGL = function() {
			modalService.openCustomDialogs({
		       "title": "title.popup.view.glentry",
		       "size" : [1200, 600],
		       "dialogsModule" : "cls.glEntry.viewGL",
		       "params": {txnId :  ctrl.settlement.settlementInfo.parentId,
		    	   txnType :  "CLS:" + ctrl.settlement.settlementInfo.parentType
		    	   }
		    });
		};
		
		ctrl.viewAmendment = function(){
			modalService.openCustomDialogs({
			   "title": "popup.title.viewamendmentlist",
			   "dialogsModule" : "cls.loan.amendmentList",
			   "size" : [1300, 300],
			   "params": {
				   "loanId" : $filter("encode")(ctrl.settlement.loan.loanInfo.loanId)
			   },
			   "btnCallback" : {
					"ok" : function() {
					}
				}	
			});
		};
		
		ctrl.settlementLoanIdLink = function(settlement){
			modalService.openCustomDialogs({
				"title" : "popup.title.loanview",
				"dialogsModule" : "cls.loan.view",
				"params" : {"loanId" : settlement.loan.loanInfo.loanId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		
		ctrl.settlementCustpayIdLink = function(settlement){
			modalService.openCustomDialogs({
				"title" : "popup.title.custpayview",
				"dialogsModule" : "cls.custpay.view",
				"params" : {"custpayId" : settlement.custpay.custpayId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		
		ctrl.settlementDchargeIdLink = function(settlement){
			modalService.openCustomDialogs({
				"title" : "popup.title.dchargeview",
				"dialogsModule" : "cls.dcharge.view",
				"params" : {"dchargeId" : settlement.dcharge.dchargeId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		
		ctrl.loanIdLink = function(currRow){
			modalService.openCustomDialogs({
				"title" : "popup.title.loanview",
				"dialogsModule" : "cls.loan.view",
				"params" : {"loanId" : currRow.loanId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		ctrl.paidloanIdLink = function(currRow){
			modalService.openCustomDialogs({
				"title" : "popup.title.loanview",
				"dialogsModule" : "cls.loan.view",
				"params" : {"loanId" : currRow.paidloanId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		ctrl.repayIdLink = function(currRow){
			modalService.openCustomDialogs({
				"title" : "popup.title.repaymentview",
				"dialogsModule" : "cls.loan.repaymentView",
				"params" : {"repayId" : currRow.repayId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		ctrl.custpayIdLink = function(currRow){
			modalService.openCustomDialogs({
				"title" : "popup.title.custpayview",
				"dialogsModule" : "cls.custpay.view",
				"params" : {"custpayId" : currRow.custpayId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		
		//settlement payment
		ctrl.swiftTypeCallBack = function(result){
			settlementPaymentService.swiftTypeCallBack(ctrl.settlement, layoutConfig, result);
		};
		
		ctrl.partyCountryChanged = function(payParty){
			settlementPaymentService.partyCountryChanged(ctrl.settlement, payParty);
		};
		
		ctrl.partyStateChanged = function(payParty){
			settlementPaymentService.partyStateChanged(ctrl.settlement, payParty);
		};
		
		ctrl.back = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else {
				modalService.openJumpDialogs({
					"messages" : [ "title.dialog.settlementsummary.back" ],
					"btnCallback" : {
						"close" : function() {}
					},
					"redirections" : [ {
						"name" : "title.infobar.settlement.payment",
						"jump" : function() {
							authService.back(ctrl.settlement).then(submitSuccessful, submitFailed);
						}
					}, {
						"name" : "title.infobar.workflow.list",
						"state" : "cls.workflow.wfTxn.list",
						"params" : {}
					}]
				});
			}
		};
		
		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.submit" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}
		
	}
})(angular);
